package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;

import cameraConfig.KameraDAO;
import cameraConfig.Standort;
import user.UserBean;

import java.util.ArrayList;
import java.util.Vector;

public class UserListController extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public void process ( HttpServletRequest request, HttpServletResponse response ) {
		ServletContext context;
		RequestDispatcher dispatcher;
		
		HttpSession session;
		
		context = getServletContext();
		session = request.getSession();
		String dispatcherTarget = "/userlist.jsp";
		String error = null;
						
		context = getServletContext();
			
		UserBean curUser = (UserBean) (session.getAttribute("user"));
		
		if(curUser != null) {
			if(curUser.isAdmin())
			{
				ArrayList<UserBean> usrs = curUser.getUsrLst();
				request.setAttribute("CurList", curUser.getUsername());
				request.setAttribute("UserList", usrs);


					String usernametoDel = request.getParameter("btnDelUser");
					String usernametoEdit = request.getParameter("btnEdituser");
					
					if(usernametoDel != null)
					{
						UserBean user = new UserBean();
						user.deleteUser(usernametoDel);
		
					}
					else if(usernametoEdit != null)
					{
						UserBean usrBean = new UserBean();
						usrBean = usrBean.getUserBean(usernametoEdit);
									
						request.setAttribute("UsernameToEdit", usernametoEdit);
						request.setAttribute("FullnameToEdit", usrBean.getFullname());
						request.setAttribute("LocationToEdit", usrBean.getLocation());
						request.setAttribute("IsAdminToEdit", Boolean.toString(usrBean.isAdmin()));
						request.setAttribute("IsInactiveToEdit", Boolean.toString(usrBean.isInactive()));
						
						KameraDAO camDoa = new KameraDAO();
						Vector<Standort> locations  = camDoa.getLocations();
						request.setAttribute("locations", locations);
						dispatcherTarget = "/edituser.jsp";		
					}
				
			}
		}
		else
		{
			error = "User session expired";
		}
		
		if (error != null && !error.isEmpty())
			request.setAttribute("errorMessage", error);
		
		dispatcher = context.getRequestDispatcher(dispatcherTarget);
				
		try {
			dispatcher.forward(request, response);
		} 
		catch (ServletException e) {
			e.printStackTrace();
			
		} 
		catch (IOException e) {
			e.printStackTrace();
		}	

	}

	public void doGet ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
	
	public void doPost ( HttpServletRequest request, HttpServletResponse response ) {
		process(request, response);
	}
}


